package com.huan.es8.indexapi;

import co.elastic.clients.elasticsearch._types.mapping.KeywordProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TextProperty;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.Alias;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.IndexSettings;
import co.elastic.clients.util.ObjectBuilder;
import com.huan.es8.AbstractEs8Api;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.function.Function;

/**
 * 创建索引
 * @author huan.fu
 * @date 2022/11/1 - 23:06
 */
public class CreateIndexTest extends AbstractEs8Api {

    @DisplayName("创建索引")
    @Test
    public void createIndex() throws IOException {

        IndexSettings indexSettings = new IndexSettings.Builder()
                .numberOfReplicas("1")
                .build();

        TypeMapping typeMapping = new TypeMapping.Builder()
                // keyword 类型的字段
                .properties("id", new Property(new KeywordProperty.Builder().build()))
                // keyword 类型的字段，且将值拷贝到 all 字段中
                .properties("name", new Property(new KeywordProperty.Builder().copyTo("all").build()))
                // keyword 类型的字段，且将值拷贝到 all 字段中，并且该字段不可搜索(index=false)
                .properties("address", new Property(new TextProperty.Builder().copyTo("all")
                        .analyzer("ik_max_word").index(false).build()))
                .properties("all", new Property(new TextProperty.Builder().build()))
                .build();

        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                // 索引的名字
                .index("index_test")
                // setting
                .settings(indexSettings)
                // mappings
                .mappings(typeMapping)
                // 给这个索引一个别名,推荐给一个别名
                .aliases("alias_index_test", new Alias.Builder().build())
                .build();

        System.err.println("request: "+ createIndexRequest);
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest);
        System.err.println("response: "+ createIndexResponse);
    }
}
